package com.graduation.community_manager.filter;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduation.community_manager.common.JWTUtil;
import com.graduation.community_manager.common.MyContextHolder;
import com.graduation.community_manager.common.ResponseUtil;
import com.graduation.community_manager.common.ResultData;
import com.graduation.community_manager.entity.CmUserEntity;
import com.graduation.community_manager.service.CmUserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wdh
 */
//@WebFilter("*")
public class JWTAuthFilter implements Filter {
    @Autowired
    CmUserService cmUserService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //从请求头中获取token
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        // 如果是登录操作直接放行
        String path = httpServletRequest.getRequestURI();
        if (path.equals("/login/action")) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = httpServletRequest.getHeader("Authorization");
        try{
            if(JWTUtil.verify(token)) {
                //成功了，从token中获取用户的信息
                String account = JWTUtil.getAccount(token);
                CmUserEntity loginuser = cmUserService.getOne(new QueryWrapper<CmUserEntity>().eq("user_name", account));
                MyContextHolder.set(loginuser);

                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                ResponseUtil.writeJson(httpServletResponse, ResultData.fail("用户没有登录，请先登录",null));
            }
        }catch (Exception e){
            if(e instanceof TokenExpiredException){

                String account = JWTUtil.getAccount(token);
                if (JWTUtil.containsToken(token)){
                    long time = (long) JWTUtil.getTime(token);
                    JWTUtil.removeToken(token);

                    if((time+JWTUtil.REFREASH_TIME) >= System.currentTimeMillis()){
                        //过期了
                        //换新的token
                        long newTime = System.currentTimeMillis();
                        String newToken = JWTUtil.createToken(account, newTime);

                        JWTUtil.saveToken(newToken, newTime);
                        //将新的token放入到头部中
                        httpServletResponse.setHeader("token",newToken);

                        //成功了，从token中获取用户的信息
                        CmUserEntity loginuser = cmUserService.getOne(new QueryWrapper<CmUserEntity>().eq("user_name", account));
                        MyContextHolder.set(loginuser);
                        //放行
                        filterChain.doFilter(servletRequest,servletResponse);
                        return;
                    }
                }

            }
            ResponseUtil.writeJson(httpServletResponse,ResultData.fail("无效token,请重新登录",null));
        }

    }
}
